from rest_framework import serializers
from .models import ArticleCollection
class CollectionSerializer(serializers.ModelSerializer):

    class Meta:
        model = ArticleCollection
        fields = ["id","name"]

    def validate(self, attrs):

        name = attrs.get("name")
        user = self.context["request"].user
        try:
            ArticleCollection.objects.get(user=user,name=name,is_deleted=False)
            raise serializers.ValidationError("文集已经存在")
        except ArticleCollection.DoesNotExist:
            return attrs

    def create(self,validated_data):

        name = validated_data.get("name")
        print(name)
        user = self.context["request"].user
        try:
            instance = ArticleCollection.objects.create(name=name,user = user)
            return instance
        except:
            raise serializers.ValidationError("添加文集失败")

    def update(self, instance, validated_data):

         instance.name = validated_data.get("name")
         instance.save()
         return instance

from .models import Article
from django.utils import timezone as datetime
class ArticleSerializer(serializers.ModelSerializer):

    isnert = serializers.BooleanField(write_only=True,required=False, default=True, help_text="新增文章的排序位置: True表示开头,False表示末尾")
    class Meta:
        model = Article
        fields = ["id","title","content","html_content","is_public","pub_date","isnert"]
        read_only=["id","title","is_public",]

    def create(self, validated_data):

        collection_id=self.context["view"].kwargs.get("collection")
        article_list = Article.objects.create(
            title= datetime.now().strftime("%Y-%m-%d"),
            user = self.context["request"].user,
            collection_id = collection_id
        )


        if not validated_data.get("insert"):
            article_list.orders = 0-article_list.id
            article_list.save()

        return article_list

from .models import ArticleImage
class ArticleImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = ArticleImage
        fields = ['image']

    def create(self, validated_data):
        # 如果希望在序列化器中获取视图中的路由参数,必须先获取视图对象
        # self.context["view"] # 调用当前序列化器的视图对象
        # self.context["request"] # 本次客户端发送的http请求
        # self.context["format"]  # 本次客户端期望服务端发送的数据格
        user_id = self.context["request"].user.id
        instance = ArticleImage.objects.create(
            image=validated_data.get("image"),
            orders=0,
            user=user_id,
        )
        instance.group = str(instance.image).split("/")[0]
        instance.save()
        return instance

from .models import ArticleSpecial
class ArticleSpecialSerializer(serializers.ModelSerializer):

    post_status = serializers.BooleanField(read_only=True,default=False,label="文章收录状态")
    class Meta:
        model=ArticleSpecial
        fields = ( "id", "name", "image", "notice", "article_count", "follow_count", "post_status")

from users.models import User
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id","username","nickname","avatar"]

from .models import ArticleCollection
class CollectionModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleCollection
        fields = ["id","name"]


class ArticleInfoSerializer(serializers.ModelSerializer):

    collection = CollectionModelSerializer()
    user = UserSerializer()
    class Meta:
        model = Article
        fields = ["id","title","html_content","user","collection","read_count","like_count","collect_count","comment_count","reward_count","created_time"]